package com.syj.collect.model;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.syj.collect.app.R;
import com.syj.collect.base.BaseActivity;
import com.syj.collect.entry.AllFragmentBean;
import com.syj.collect.entry.TaskBean;
import com.syj.collect.entry.UserInfoBean;
import com.syj.collect.http.BaseObserver;
import com.syj.collect.http.BaseRequest;
import com.syj.collect.utils.GsonUtil;
import com.syj.collect.utils.SPUtil;
import com.syj.collect.utils.ToastMgr;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MyTaskDetailsActivity extends BaseActivity {

    TaskBean.DataBean.ListBean dataBean;
    private WebView web;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_detalis);
        initTitle("我的任务");
        dataBean = (TaskBean.DataBean.ListBean) getIntent().getSerializableExtra("data");
        initView();
//        getLatlon("保定");//需要修改城市名字。
    }


    private TextView tv_name;
    private TextView tv_address;
    private TextView tv_start_data;
    private TextView tv_end_data;
    private TextView go_task_tv;

    private void initView() {
        tv_name = findViewById(R.id.tv_name);
//        web = findViewById(R.id.webview);

        tv_address = findViewById(R.id.tv_address);
        tv_start_data = findViewById(R.id.tv_start_data);
        tv_end_data = findViewById(R.id.tv_end_data);

        tv_name.setText(dataBean.getName());
        tv_start_data.setText(dataBean.getStartTime());
        tv_end_data.setText(dataBean.getEndTime());

        if (dataBean.getAddressList()!=null&&!dataBean.getAddressList().isEmpty()){
            tv_address.setText(dataBean.getAddressList().get(0).getAddress());
        }




        go_task_tv = findViewById(R.id.go_task_tv);
//        String ss = "http://uri.amap.com/navigation?from=116.478346,39.997361,startpoint&to=116.3246,39.966577,endpoint&via=116.402796,39.936915,midwaypoint&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0";
//        WebSettings webSettings = web.getSettings();
//        webSettings.setSupportZoom(true);
////设置是否可缩放，会出现缩放工具（若为true则上面的设值也默认为true）
//        webSettings.setBuiltInZoomControls(true);
//
//        webSettings.setJavaScriptEnabled(true);
//
//        webSettings.setDomStorageEnabled(true);
//        webSettings.setDatabaseEnabled(true);


        //webSettings.setGeolocationEnabled(true);


//        web.loadUrl(ss);
//        web.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                Uri uri = Uri.parse(url);
//
//                if (!"http".equals(uri.getScheme()) || !"https".equals(uri.getScheme())) {
//                    return false;
//                } else {
//                    view.loadUrl(url);
//                    return true;
//                }
//
//            }
//        });
        go_task_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isAvilible(MyTaskDetailsActivity.this,"com.autonavi.minimap")){
                    ToastMgr.builder.display("您还没有安装高德地图");
                    return;
                }
                updataTask();
                if (dataBean.getAddressList()==null||dataBean.getAddressList().isEmpty()){
                    return;
                }

                StringBuffer stringBuffer = new StringBuffer("androidamap://route?sourceApplication=").append("amap");
                stringBuffer.append("&dlat=").append(dataBean.getAddressList().get(0).getLat())
                        .append("&dlon=").append(dataBean.getAddressList().get(0).getLon())
                        .append("&dname=").append(dataBean.getAddressList().get(0).getAddress())
                        .append("&dev=").append(0)
                        .append("&t=").append(0);

                Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
                intent.setPackage("com.autonavi.minimap");
                startActivity(intent);


            }
        });
    }

    private void updataTask() {

        HashMap hashMap = new HashMap();
        hashMap.put("id", dataBean.getId());
        hashMap.put("status","3");
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), GsonUtil.gsonString(hashMap));
        BaseRequest.getInstance().getApiServise().updataTask(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("task1结果?", value);
                        try {
                            JSONObject jsonObject=new JSONObject(value);
                            int code = jsonObject.getInt("code");
                            if (code==0){
                                MyTaskDetailsActivity.this.finish();
                            }else {
                                ToastMgr.builder.display("网络异常稍后在试一试");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return false;
                    }
                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        //view.initFail("网络异常");
                    }
                    @Override
                    public void onEnd() {

                    }
                });
    }

    private boolean isAvilible(Context context, String packageName){
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if(packageInfos != null){
            for(int i = 0; i < packageInfos.size(); i++){
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);









//    packageName    private void getLatlon(String cityName) {
//
//        GeocodeSearch geocodeSearch = new GeocodeSearch(this);
//        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
//            @Override
//            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
//
//            }
//
//            @Override
//            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
//
//
//                if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
//                        geocodeResult.getGeocodeAddressList().size() > 0) {
//
//                    GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
//                    double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
//                    double longititude = geocodeAddress.getLatLonPoint().getLongitude();//经度
//                    String adcode = geocodeAddress.getAdcode();//区域编码
//
//
//                    Log.e("地理编码", geocodeAddress.getAdcode() + "");
//                    Log.e("纬度latitude", latitude + "");
//                    Log.e("经度longititude", longititude + "");
//
//                } else {
////                        ToastUtils.show(context,"地址名出错");∂
//                    Log.e("经度longititude", "地址名出错");
//                }
//
//            }
//        });
//
//        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName.trim(), "29");
//        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);


    }


}
